/*
 * Copyright (c) 2022 Hunan OpenValley Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include "cmsis_os2.h"
#include "ohos_run.h"
#include <stdio.h>
#include "driver/uart.h"
#include "driver/gpio.h"
#include "sdkconfig.h"
#include "esp_log.h"

#define SYS_DELAY_TICKS 200
#define TASK_STACK_SIZE 4096
#define TASK_PRIO 25
#define BUFF_MAX_SIZE 128
#define UART_BAUDRATE 115200

#define UART_INDEX 0 // 串口号

osThreadId_t g_taskID = NULL;

// 定义串口的引脚
#define ECHO_TEST_TXD (GPIO_NUM_32)
#define ECHO_TEST_RXD (GPIO_NUM_33)
#define ECHO_TEST_RTS (UART_PIN_NO_CHANGE)
#define ECHO_TEST_CTS (UART_PIN_NO_CHANGE)

#define ECHO_UART_PORT_NUM (UART_NUM_1)
#define ECHO_UART_BAUD_RATE (115200)

#define BUF_SIZE (1024)

static void uart_test(void)
{
    /* Configure parameters of an UART driver,
     * communication pins and install the driver */
    uart_config_t uart_config = {
        .baud_rate = ECHO_UART_BAUD_RATE,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
    };
    int intr_alloc_flags = 0;

#if CONFIG_UART_ISR_IN_IRAM
    intr_alloc_flags = ESP_INTR_FLAG_IRAM;
#endif

    ESP_ERROR_CHECK(uart_driver_install(ECHO_UART_PORT_NUM, BUF_SIZE, BUF_SIZE, 0, NULL, intr_alloc_flags));
    ESP_ERROR_CHECK(uart_param_config(ECHO_UART_PORT_NUM, &uart_config));
    ESP_ERROR_CHECK(uart_set_pin(ECHO_UART_PORT_NUM, ECHO_TEST_TXD, ECHO_TEST_RXD, ECHO_TEST_RTS, ECHO_TEST_CTS));

    // Configure a temporary buffer for the incoming data
    uint8_t *data = (uint8_t *)malloc(BUF_SIZE);

    printf("start recv nbiot!\n");

    // Write data back to the UART
    uart_write_bytes(ECHO_UART_PORT_NUM, "AT\r\n", strlen("AT\r\n"));

    // Read data from the UART
    int len = uart_read_bytes(ECHO_UART_PORT_NUM, data, (BUF_SIZE - 1), 20 / portTICK_PERIOD_MS);

    if (len)
    {
        data[len] = '\0';
        printf("Recv str: %s\r\n", (char *)data);
    }

    // 取消回显
    uart_write_bytes(ECHO_UART_PORT_NUM, "ATE0\r\n", strlen("ATE0\r\n"));

    // 询问SIM卡激活情况
    uart_write_bytes(ECHO_UART_PORT_NUM, "AT+CPIN?\r\n", strlen("AT+CPIN?\r\n"));
    len = uart_read_bytes(ECHO_UART_PORT_NUM, data, (BUF_SIZE - 1), 20 / portTICK_PERIOD_MS);
    if (len)
    {
        data[len] = '\0';
        printf("%s\r\n", (char *)data);
    }

    // 询问模块注册情况
    uart_write_bytes(ECHO_UART_PORT_NUM, "AT+CREG?\r\n", strlen("AT+CREG?\r\n"));
    len = uart_read_bytes(ECHO_UART_PORT_NUM, data, (BUF_SIZE - 1), 20 / portTICK_PERIOD_MS);
    if (len)
    {
        data[len] = '\0';
        printf("%s\r\n", (char *)data);
    }

    // 此处需要休眠10秒，等待模块初始化完成
    sleep(10);
    // 询问模块注册情况
    uart_write_bytes(ECHO_UART_PORT_NUM, "AT+CREG?\r\n", strlen("AT+CREG?\r\n"));
    len = uart_read_bytes(ECHO_UART_PORT_NUM, data, (BUF_SIZE - 1), 20 / portTICK_PERIOD_MS);
    if (len)
    {
        data[len] = '\0';
        printf("%s\r\n", (char *)data);
    }

    // 创建链接
    uart_write_bytes(ECHO_UART_PORT_NUM, "AT+SKTCREATE=1,1,6\r\n", strlen("AT+SKTCREATE=1,1,6\r\n"));
    // 等待2秒
    sleep(2);
    // 链接到TCP服务器 AT+SKTCONNECT=0,8.135.10.183,31217
    uart_write_bytes(ECHO_UART_PORT_NUM, "AT+SKTCONNECT=0,8.135.10.183,31217\r\n", strlen("AT+SKTCONNECT=0,8.135.10.183,31217\r\n"));
    len = uart_read_bytes(ECHO_UART_PORT_NUM, data, (BUF_SIZE - 1), 20 / portTICK_PERIOD_MS);
    if (len)
    {
        data[len] = '\0';
        printf("%s\r\n", (char *)data);
    }

    // 这里可以接受TCP数据了
    while (1)
    {
        // Read data from the UART
        len = uart_read_bytes(ECHO_UART_PORT_NUM, data, (BUF_SIZE - 1), 20 / portTICK_PERIOD_MS);

        if (len)
        {
            data[len] = '\0';
            printf("Recv str: %s\r\n", (char *)data);
        }
    }

    return;
}

#define AT_CMD_MAX_LEN 256
// TCP发送数据
int send_tcp_message(char *msg)
{
    unsigned char ret;
    char at_sktsend[AT_CMD_MAX_LEN] = {'\0'};
    char hex_str[65] = {'\0'};

    if (msg == NULL)
    {
        return -1;
    }
    ret = str2hex(msg, hex_str, 65);
    if (ret != 1)
    {
        return -2;
    }
    snprintf(at_sktsend, AT_CMD_MAX_LEN, "AT+SKTSEND=0,%d,%s\r\n", strlen(msg), hex_str);
    printf("at_sktsend:%s\r\n", at_sktsend);
    uart_write_bytes(ECHO_UART_PORT_NUM, at_sktsend, strlen(at_sktsend));
}

static void uart_example_task(void)
{
    printf("into uart hdf example!\n");
    osThreadAttr_t attr;
    attr.name = "uart_test";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = TASK_STACK_SIZE;
    attr.priority = TASK_PRIO;
    g_taskID = osThreadNew((osThreadFunc_t)uart_test, NULL, &attr);
    if (g_taskID == NULL)
    {
        printf("Failed to create Test Uart thread!\n");
    }
}

OHOS_APP_RUN(uart_example_task);
